import os.path
import time
import setting
from flask import Blueprint, json, request
from server.module.textChat.textStore import TextStore
from server.utils.mylog import mylog

chat = Blueprint('chat', __name__, url_prefix=setting.prefixURL + '/chat/')

textStore = TextStore()


@chat.route('/queryText', methods=['get'])
def axg_query_text_flow():
    return json.dumps(textStore.word)


@chat.route('/submitText', methods=['post'])
def axp_submit_text():
    def processIP():
        if request.headers.get('flagship'):
            return request.headers.get('flagship')
        else:
            return request.remote_addr

    ##############
    data = json.loads(request.data)
    mylog.info(f'[{request.remote_addr}]Received text:{data["content"]}')
    textStore.word.append({
        'time': int(time.time() * 1000),
        # 'time': data['time'],
        'from': processIP(),
        'content': data['content']
    })

    return 'ok'


@chat.route('/clearText', methods=['get'])
def axp_clear_text():
    mylog.warn(f'[{request.remote_addr}]text cleared')
    textStore.word = []
    # print(textStore.word)
    return 'ok'


@chat.route('/saveAsFile', methods=['get'])
def axp_save_text():
    if request.args.get('type') == 'd':
        dir = setting.DownloadPath
    else:
        dir = setting.UploadPath
    newfile = os.path.join(dir, str(time.strftime("%Y%m%d-%H%M%S", time.localtime())) + '.json')
    textStore = TextStore()
    with open(newfile, 'w') as f:
        json.dumps(textStore.word, f)
    mylog.data('Saved text chat')
    return 'ok'
